<template>
  <div class="vehicle-monitoring">
    <!-- 地图容器 -->
    <div id="map" class="map-container" />

    <!-- 控制面板 -->
    <div class="control-panel">
      <el-button class="control-btn" @click="toggleHeatmap">
        {{ heatmapVisible ? "隐藏热力图" : "显示热力图" }}
      </el-button>
      <el-button class="control-btn" @click="showPerformanceMetrics">
        性能指标
      </el-button>
      <el-select
        v-model="selectedVehicle"
        placeholder="选择车辆"
        @change="handleVehicleChange"
      >
        <el-option
          v-for="vehicle in vehicles"
          :key="vehicle.id"
          :label="vehicle.name"
          :value="vehicle.id"
        />
      </el-select>
    </div>

    <!-- 视频播放弹窗 -->
    <el-dialog
      v-model="videoDialogVisible"
      title="车辆监控视频"
      :width="videoWidth"
      @close="handleVideoClose"
    >
      <div class="video-container">
        <video ref="videoPlayer" class="video-player" controls />
        <div v-if="videoMonitor.state.isLoading" class="video-loading">
          <el-progress
            :percentage="videoMonitor.state.loadProgress"
            stroke-width="4"
          />
          <p>正在加载视频流... {{ videoMonitor.state.loadProgress }}%</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="handleVideoClose">关闭</el-button>
        <el-button type="primary" @click="videoMonitor.switchQuality">
          切换清晰度 ({{ videoMonitor.state.currentQuality }})
        </el-button>
      </template>
    </el-dialog>

    <!-- 性能指标弹窗 -->
    <el-dialog
      v-model="performanceDialogVisible"
      title="系统性能指标"
      width="600px"
    >
      <div class="performance-metrics">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="metric-card">
              <h3>地图性能</h3>
              <p>帧率: {{ mapPerf.mapFps.toFixed(1) }} FPS</p>
              <p>加载时间: {{ mapPerf.mapLoadTime }} ms</p>
              <p>标记点数量: {{ mapPerf.markerCount }}</p>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="metric-card">
              <h3>视频性能</h3>
              <p>加载延迟: {{ videoMonitor.state.loadLatency }} ms</p>
              <p>缓冲时间: {{ videoMonitor.state.bufferTime }} ms</p>
              <p>当前码率: {{ videoMonitor.state.bitrate }} kbps</p>
            </div>
          </el-col>
        </el-row>
        <div class="metrics-chart">
          <h3>最近30秒帧率变化</h3>
          <el-progress
            v-for="(fps, index) in mapPerf.recentFps"
            :key="index"
            :percentage="Math.min(100, fps * 2)"
            stroke-width="6"
            style="margin-bottom: 4px"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import { MarkerClusterGroup } from "leaflet.markercluster";
import { useVideoMonitor } from "./useVideoMonitor";
import { useMapPerformance } from "./useMapPerformance";
import * as Sentry from "@sentry/browser";
// 在地图组件中使用
import { useMapPerformance } from "./useMapPerformance";

// 初始化性能监控，可自定义配置
const {
  performanceData,
  updateMarkerCount,
  recordMapLoadTime,
  recordRenderTime,
  startMonitoring
} = useMapPerformance({
  lowFpsThreshold: 20, // 帧率低于20视为低性能
  maxFpsHistory: 60 // 保留60条历史记录
});

// 地图初始化时
onMounted(async () => {
  const mapStartTime = performance.now();

  // 初始化地图（以Leaflet为例）
  const map = L.map("map").setView([39.9042, 116.4074], 12);

  // 监听地图渲染事件，主动上报渲染时间
  map.on("move", recordRenderTime); // 地图移动时
  map.on("zoom", recordRenderTime); // 地图缩放时
  map.on("layeradd", recordRenderTime); // 添加图层时

  // 记录地图加载完成时间
  map.on("load", () => {
    recordMapLoadTime(mapStartTime);
  });

  // 更新标记点数量
  updateMarkerCount(vehicles.value.length);

  // 开始监控
  startMonitoring();
});
// 初始化Sentry性能监控
Sentry.init({
  dsn: "YOUR_SENTRY_DSN", // 替换为你的Sentry DSN
  integrations: [new Sentry.BrowserTracing(), new Sentry.Replay()],
  tracesSampleRate: 1.0,
  replaySampleRate: 0.1
});

// 初始化Hooks
const videoMonitor = useVideoMonitor({
  preloadExpireTime: 5 * 60 * 1000, // 5分钟缓存过期
  maxPreloadCount: 10, // 最多预加载10个视频源
  hlsConfig: {
    maxBufferLength: 30,
    maxMaxBufferLength: 60,
    startLevel: -1
  }
});

const mapPerf = useMapPerformance();

// 组件状态
const map = ref<L.Map | null>(null);
const markerCluster = ref<MarkerClusterGroup | null>(null);
const heatmapLayer = ref<any>(null);
const heatmapVisible = ref(true);
const videoDialogVisible = ref(false);
const performanceDialogVisible = ref(false);
const selectedVehicle = ref("");
const videoPlayer = ref<HTMLVideoElement | null>(null);
const videoWidth = ref("80%");

// 车辆数据
const vehicles = ref([
  { id: "v1", name: "配送车-001", lat: 39.9042, lng: 116.4074, online: true },
  { id: "v2", name: "配送车-002", lat: 39.9165, lng: 116.3972, online: true },
  { id: "v3", name: "配送车-003", lat: 39.9962, lng: 116.3427, online: false },
  { id: "v4", name: "配送车-004", lat: 39.9092, lng: 116.4422, online: true },
  { id: "v5", name: "配送车-005", lat: 39.9507, lng: 116.4372, online: true }
]);

onMounted(async () => {
  // 注册视频源
  const videoSources = vehicles.value.map(vehicle => ({
    id: vehicle.id,
    url: `https://your-video-server.com/stream/${vehicle.id}/master.m3u8`,
    thumbnailUrl: `https://your-server.com/thumbnails/${vehicle.id}.jpg`
  }));

  videoMonitor.registerVideoSources(videoSources);

  // 初始化视频元素
  videoMonitor.setVideoElement(videoPlayer.value);

  // 初始化地图
  const mapStartTime = performance.now();
  map.value = L.map("map").setView([39.9042, 116.4074], 12);

  // 添加高德地图图层
  L.tileLayer(
    "https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    {
      subdomains: "1234",
      attribution: "© 高德地图"
    }
  ).addTo(map.value);

  // 创建标记点集群
  markerCluster.value = L.markerClusterGroup({
    disableClusteringAtZoom: 16,
    showCoverageOnHover: false,
    iconCreateFunction: cluster => {
      return L.divIcon({
        html: `<div class="cluster-icon">${cluster.getChildCount()}</div>`,
        className: "custom-cluster-icon",
        iconSize: L.point(40, 40)
      });
    }
  });

  // 添加车辆标记
  vehicles.value.forEach(vehicle => {
    addVehicleMarker(vehicle);
  });

  markerCluster.value.addTo(map.value);
  mapPerf.updateMarkerCount(vehicles.value.length);

  // 记录地图加载时间
  mapPerf.recordMapLoadTime(mapStartTime);

  // 开始性能监控
  mapPerf.startMonitoring();

  // 监听地图视野变化，预加载可见范围内的车辆视频
  map.value.on("moveend", handleMapMove);

  // 初始预加载
  handleMapMove();
});

// 添加车辆标记
function addVehicleMarker(vehicle: any) {
  if (!markerCluster.value) return;

  const icon = L.divIcon({
    html: `<div class="vehicle-marker ${vehicle.online ? "online" : "offline"}">
            <i class="fa fa-truck"></i>
          </div>`,
    className: "custom-vehicle-marker",
    iconSize: L.point(36, 36)
  });

  const marker = L.marker([vehicle.lat, vehicle.lng], { icon });

  // 标记点击事件 - 播放视频
  marker.on("click", () => {
    selectedVehicle.value = vehicle.id;
    playVehicleVideo(vehicle.id);
  });

  // 鼠标悬停 - 预加载视频
  marker.on("mouseover", () => {
    if (vehicle.online) {
      videoMonitor.preloadVideo(vehicle.id);
    }
  });

  markerCluster.value.addLayer(marker);
}

// 处理地图移动，预加载视野内的车辆视频
function handleMapMove() {
  if (!map.value) return;

  const visibleBounds = map.value.getBounds();
  const visibleVehicles = vehicles.value.filter(vehicle => {
    return vehicle.online && visibleBounds.contains([vehicle.lat, vehicle.lng]);
  });

  // 预加载视野内的前3辆在线车辆
  if (visibleVehicles.length > 0) {
    videoMonitor.preloadVideos(visibleVehicles.slice(0, 3).map(v => v.id));
  }
}

// 播放车辆视频
async function playVehicleVideo(vehicleId: string) {
  const success = await videoMonitor.playVideo(vehicleId);
  if (success) {
    videoDialogVisible.value = true;
  }
}

// 关闭视频弹窗
function handleVideoClose() {
  videoMonitor.stopVideo();
  videoDialogVisible.value = false;
}

// 显示性能指标
function showPerformanceMetrics() {
  performanceDialogVisible.value = true;
}

// 处理车辆选择变化
function handleVehicleChange(vehicleId: string) {
  const vehicle = vehicles.value.find(v => v.id === vehicleId);
  if (vehicle) {
    // 移动地图到选中车辆位置
    map.value?.setView([vehicle.lat, vehicle.lng], 16);
    // 播放视频
    playVehicleVideo(vehicleId);
  }
}

// 切换热力图显示
function toggleHeatmap() {
  heatmapVisible.value = !heatmapVisible.value;
  // 这里可以添加实际的热力图显示/隐藏逻辑
}

// 清理资源
onUnmounted(() => {
  if (map.value) {
    map.value.remove();
  }
  videoMonitor.stopVideo();
  mapPerf.stopMonitoring();
});

// 监听窗口大小变化
watch(
  () => window.innerWidth,
  () => {
    nextTick(() => {
      map.value?.invalidateSize();
      // 根据窗口大小调整视频宽度
      videoWidth.value = window.innerWidth > 1200 ? "80%" : "95%";
    });
  }
);

// 监听视频元素引用变化
watch(videoPlayer, newEl => {
  videoMonitor.setVideoElement(newEl);
});
</script>

<style scoped>
.vehicle-monitoring {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
  z-index: 1;
}

.control-panel {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 1000;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.control-btn {
  background-color: white;
  border: 1px solid #ccc;
}

.video-container {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 比例 */
}

.video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.video-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  gap: 15px;
  z-index: 10;
}

.performance-metrics {
  padding: 10px 0;
}

.metric-card {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 15px;
}

.metric-card h3 {
  margin-bottom: 10px;
  color: #333;
  font-size: 16px;
}

.metric-card p {
  margin: 5px 0;
  font-size: 14px;
}

.metrics-chart {
  margin-top: 20px;
}

/* 车辆标记样式 */
:deep(.custom-vehicle-marker) {
  text-align: center;
  font-weight: bold;
}

:deep(.vehicle-marker) {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

:deep(.vehicle-marker.online) {
  background-color: #42b983;
}

:deep(.vehicle-marker.offline) {
  background-color: #999;
}

/* 集群标记样式 */
:deep(.custom-cluster-icon) {
  width: 40px;
  height: 40px;
  background-color: #3b82f6;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
</style>
